﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WebApi.Helpers;
using WebApi.Model;
using WebApi.ViewModel;

namespace WebApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ReportController : BaseController
    {
        public ReportController(ILogger<ReportController> logger) : base(logger)
        {
        }

        [HttpPost("Add")]
        public async Task<ReturnModel> Add(Report model)
        {
            return await Save(model, true);
        }

        [HttpPost("Update")]
        public async Task<ReturnModel> Update(Report model)
        {
            return await Save(model, false);
        }

        /// <summary>
        /// 保存数据
        /// </summary>
        /// <param name="model"></param>
        /// <param name="isInsert"></param>
        /// <returns></returns>
        private async Task<ReturnModel> Save(Report model, bool isInsert)
        {
            try
            {
                if (DbHelper.Report.IsAny(c => c.RptName == model.RptName && c.ScaleCode == model.ScaleCode && c.Id != model.Id))
                    return logger.Code_202("报表名称已存在");
                else if (isInsert)
                    await DbHelper.Report.InsertAsync(model);
                else
                    await DbHelper.GetDbConn().Updateable(model).UpdateColumns(it => new { it.RptName, it.RptFileName }).ExecuteCommandAsync();
                LogToDB("Report", isInsert ? "新增" : "更新", $"参数：{JsonConvert.SerializeObject(model)}", "成功");
                return new ReturnModel { Count = 1 };
            }
            catch (Exception ex)
            {
                LogToDB("Report", isInsert ? "新增" : "更新", $"参数：{JsonConvert.SerializeObject(model)}", "异常", $"{nameof(Save)}-{ex.Message}");
                return logger.ErrorModel(nameof(ReportController) + "-" + nameof(Save), ex);
            }
        }

        [HttpPost("Delete/{id}")]
        public async Task<ReturnModel> Delete(int id)
        {
            try
            {
                Report model = DbHelper.Report.GetById(id);
                await DbHelper.Report.DeleteAsync(it => it.Id == id);
                LogToDB("Report", "删除", $"参数：{id},删除数据：{JsonConvert.SerializeObject(model)}", "成功");
                return new ReturnModel { Count = 1 };
            }
            catch (Exception ex)
            {
                LogToDB("Report", "删除", $"参数：{id}", "异常", $"{nameof(Delete)}-{ex.Message}");
                return logger.ErrorModel($"{nameof(ReportController)}/{nameof(Delete)}", ex);
            }
        }

        /// <summary>
        /// 获取报表数据列表
        /// </summary>
        /// <returns></returns>
        [HttpPost("GetList")]
        public async Task<ReturnModel> GetList(Report model)
        {
            try
            {
                var filter = Expressionable.Create<Report>();
                filter.AndIF(!string.IsNullOrEmpty(model.RptName), it => it.RptName.Contains(model.RptName));
                filter.AndIF(model.RptType != 0, it => it.RptType == model.RptType);
                if (string.IsNullOrEmpty(model.ScaleCode))
                    filter.And(it => SqlFunc.IsNullOrEmpty(it.ScaleCode));
                else
                    filter.And(it => SqlFunc.IsNullOrEmpty(it.ScaleCode) || it.ScaleCode == model.ScaleCode);
                var data = await DbHelper.Report.AsQueryable().Where(filter.ToExpression()).OrderBy(it => it.OrderNum).ToListAsync();
                return new ReturnModel { Count = data.Count, Data = data };
            }
            catch (Exception ex)
            {
                LogToDB("Report", "查询", $"参数：", "异常", $"{nameof(GetList)}-{ex.Message}");
                return logger.ErrorModel($"{nameof(ReportController)}/{nameof(GetList)}", ex);
            }
        }

        /// <summary>
        /// 查询报表列表
        /// </summary>
        /// <param name="query">查询条件</param>
        /// <returns></returns>
        [HttpPost("GetReportList")]
        public async Task<ReturnModel> GetReportList(QueryReportVM query)
        {
            try
            {
                logger.LogDebug(JsonConvert.SerializeObject(query));
                Tuple<string, List<SqlSugar.SugarParameter>> tuple = CreateQuery(query);
                if (tuple.Item2 != null)
                {
                    var data = await DbHelper.GetDbConn().Ado.SqlQueryAsync<WeightRecord>(tuple.Item1, tuple.Item2);
                    return new ReturnModel { Count = data.Count, Data = data };
                }
                else
                    return new ReturnModel { Code = 500, Message = tuple.Item1 };
            }
            catch (Exception ex)
            {
                LogToDB("Report", "查询", $"参数：", "异常", $"{nameof(GetReportList)}-{ex.Message}");
                return logger.ErrorModel($"{nameof(ReportController)}/{nameof(GetReportList)}", ex);
            }
        }

        /// <summary>
        /// 生成查询Sql语句
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        private Tuple<string, List<SqlSugar.SugarParameter>> CreateQuery(QueryReportVM query)
        {
            StringBuilder sql = new StringBuilder(query.PrevWhere);
            List<SqlSugar.SugarParameter> paras = new List<SqlSugar.SugarParameter>();
            try
            {
                sql.Append(" AND t_WeightRecord.UpdateTime >=@Start AND t_WeightRecord.UpdateTime<=@End");
                paras.Add(new SqlSugar.SugarParameter("@Start", query.Start));
                paras.Add(new SqlSugar.SugarParameter("@End", query.End));
                AddParas(query.Where1);
                AddParas(query.Where2);
                AddParas(query.Where3);
                AddParas(query.Where4);
                AddParas(query.Where5);
                AddParas(query.Where6);
                sql.Append(" ");
                sql.Append(query.NextWhere ?? "");
                logger.LogInformation(sql.ToString());
                logger.LogInformation(JsonConvert.SerializeObject(paras.Select(it => new { ParameterName = it.ParameterName, Value = it.Value })));
                return new Tuple<string, List<SqlSugar.SugarParameter>>(sql.ToString(), paras);
            }
            catch (Exception ex)
            {
                LogToDB("Report", "查询", $"参数：{JsonConvert.SerializeObject(query)}", "异常", $"{nameof(CreateQuery)}-{ex.Message}");
                return new Tuple<string, List<SqlSugar.SugarParameter>>(ex.Message, null);
            }

            void AddParas(QueryReportVM.ReportWhereModel where)
            {
                if (where != null && !string.IsNullOrWhiteSpace(where.Value))
                {
                    sql.Append(" AND ");
                    sql.Append(where.FieldInfo.Field);

                    if (where.FieldInfo.Field == "t_WeightRecord.ScaleFlag")
                    {
                        where.Value = where.Value.Replace('，', ',').Replace("汽车衡", "");
                        string[] flags = where.Value.Split(',');
                        flags = flags.Select(w => "汽车衡" + w).ToArray();
                        string parameterNames = string.Join(",", flags.Select((_, i) => "@param" + i.ToString()));

                        sql.Append($" IN({parameterNames}) ");
                        for (int i = 0; i < flags.Length; i++)
                        {
                            paras.Add(new SqlSugar.SugarParameter("@param" + i.ToString(), flags[i]));
                        }
                    }
                    else
                    {
                        if (where.FieldInfo.SelectType == 0)
                        {
                            sql.Append("=@");
                            sql.Append(where.FieldInfo.Field.Replace(".", ""));
                            if (where.FieldInfo.Field == "t_WeightRecord.IsComplete")
                            {
                                if (where.Value == "完成") where.Value = "1";
                                else if (where.Value == "未完成") where.Value = "0";
                            }
                        }
                        else if (where.FieldInfo.SelectType == 1)
                        {
                            sql.Append(" LIKE '%'+@");
                            sql.Append(where.FieldInfo.Field.Replace(".", ""));
                            sql.Append("+'%'");
                        }
                        else if (where.FieldInfo.SelectType == 2)
                        {
                            sql.Append(" >= @");
                            sql.Append(where.FieldInfo.Field.Replace(".", ""));
                            if (!string.IsNullOrWhiteSpace(where.Value2))
                            {
                                //加载第二参数
                                sql.Append(" AND ");
                                sql.Append(where.FieldInfo.Field);
                                sql.Append(" <= @");
                                sql.Append(where.FieldInfo.Field.Replace(".", "2"));
                                paras.Add(new SqlSugar.SugarParameter("@" + where.FieldInfo.Field.Replace(".", "2"), where.Value2));
                            }
                        }
                        paras.Add(new SqlSugar.SugarParameter("@" + where.FieldInfo.Field.Replace(".", ""), where.Value));
                    }
                }
            }
        }
    }
}
